#!/usr/bin/env bash
#
# Copyright © 2014 Jesse 'Jeaye' Wilkerson
# See licensing in LICENSE file, or at:
#   http://www.opensource.org/licenses/MIT
#
# File: do_link
# Author: Jesse 'Jeaye' Wilkerson

# XXX: Do not call this script directly: use `make generate`
set -o errexit
set -o nounset

tmp_man=$1

# Map basic types to their common typedefs and create links
# for each of the occurring patterns in the man pages.
# NOTE: There is likely a better way to do this. I realize.
declare -a typedefs=('basic_string' 'basic_string_view'\
                     'basic_istringstream' 'basic_ostringstream' 'basic_stringstream'\
                     'basic_istream' 'basic_ostream' 'basic_iostream'\
                     'basic_ifstream' 'basic_ofstream' 'basic_fstream'\
                     'basic_stringbuf' 'basic_streambuf' 'basic_ios'\
                     'basic_filebuf' 'basic_regex'
                    )
declare -a alias_basic_string=('string' 'wstring' 'u16string' 'u32string')
declare -a alias_basic_string_view=('string_view' 'wstring_view' 'u16string_view' 'u32string_view')
declare -a alias_basic_stringstream=('stringstream' 'wstringstream')
declare -a alias_basic_istringstream=('istringstream' 'wistringstream')
declare -a alias_basic_ostringstream=('ostringstream' 'wostringstream')
declare -a alias_basic_istream=('istream' 'wistream')
declare -a alias_basic_ostream=('ostream' 'wostream')
declare -a alias_basic_iostream=('iostream' 'wiostream')
declare -a alias_basic_ifstream=('ifstream' 'wifstream')
declare -a alias_basic_ofstream=('ofstream' 'wofstream')
declare -a alias_basic_fstream=('fstream' 'wfstream')
declare -a alias_basic_stringbuf=('stringbuf' 'wstringbuf')
declare -a alias_basic_streambuf=('streambuf' 'wstreambuf')
declare -a alias_basic_ios=('ios' 'wios')
declare -a alias_basic_filebuf=('filebuf' 'wfilebuf')
declare -a alias_basic_regex=('regex' 'wregex')

for td in "${typedefs[@]}"
do
  # Link class pages (eg. std::string.3)
  tmp=alias_$td[@]
  for al in "${!tmp}"
  do
    # Class file
    file=$tmp_man/std::$td.3
    if [ -f $file ];
    then
      out="${file/$td/$al}"
      rm -f $out
      ln -s $(basename $file) $out
    fi

    # Constructor
    file=$tmp_man/std::$td::$td.3
    if [ -f $file ];
    then
      out="${file//$td/$al}"
      rm -f $out
      ln -s $(basename $file) $out
    fi
  done

  # Link member pages (eg. std::string::erase.3)
  for file in $(find $tmp_man -name "*$td::*");
  do
    tmp=alias_$td[@]
    for al in "${!tmp}"
    do
      out="${file/$td/$al}"
      rm -f $out
      ln -s $(basename $file) $out
    done
  done
done

ln -s "std::find,std::find_if,std::find_if_not.3" "$tmp_man/std::find.3"
ln -s "std::find,std::find_if,std::find_if_not.3" "$tmp_man/std::find_if.3"
ln -s "std::find,std::find_if,std::find_if_not.3" "$tmp_man/std::find_if_not.3"
